/**留言相关 */
const router = require('koa-router')();
const DB = require('../db');
const { hot1, hot2, hot3 } = require('../utils/leaveMessageHotConfig');

/**
 * 发布留言
 * @param {string} title 标题
 * @param {string} content 内容
 */
router.post('/publishLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { title, content } = ctx.request.body;
  if (!title || !content) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('users', { userName });
  const addData = {
    key: String(Date.now()) + userName,
    publishDate: Date.now(),
    userName,
    uid: r0[0].uid,
    avatarUrl: r0[0].avatarUrl,
    title,
    content,
    likeNum: 0,
    likeList: [],
    isAccepted: false
  };
  await DB.add('leaveMessage', addData);
  const r1 = await DB.find('leaveMessageRank', { userName });
  if (r1 && r1.length > 0) {
    const updateObj = {
      leaveMessageNumber: r1[0].leaveMessageNumber + 1,
      hotNumber: r1[0].hotNumber + 1 * hot1
    };
    await DB.updateValue('leaveMessageRank', { userName }, updateObj);
  } else {
    const rankData = {
      userName,
      uid: r0[0].uid,
      avatarUrl: r0[0].avatarUrl,
      leaveMessageNumber: 1,
      acceptedNumber: 0,
      likedNumber: 0,
      hotNumber: 1 * hot1
    };
    await DB.add('leaveMessageRank', rankData);
  }
  ctx.body = {
    code: '0000',
    message: '发布成功',
    data: addData
  }
})

/**
 * 获取某条留言（查看/修改时）
 * @param {string} id 对应key值
 */
router.get('/getOneLeaveMessage', async (ctx, next) => {
  const { id } = ctx.query;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言',
      data: {}
    }
    return;
  }
  ctx.body = {
    code: '0000',
    message: '获取成功',
    data: r0[0]
  }
})

/**
 * 获取所有留言
 */
router.get('/getAllLeaveMessages', async (ctx, next) => {
  const r0 = await DB.find('leaveMessage');
  const r1 = r0.sort((a, b) => b.publishDate - a.publishDate);
  ctx.body = {
    code: '0000',
    message: '获取成功',
    data: r1
  }
})

/**
 * 删除某条留言
 * @param {string} id 对应key值
 */
router.post('/deleteOneLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言',
      data: {}
    }
    return;
  }
  await DB.delOne('leaveMessage', { key: id });
  const { isAccepted, likeNum } = r0[0];
  const r1 = await DB.find('leaveMessageRank', { userName: r0[0].userName });
  if (!r1 || r1.length === 0) {
    ctx.body = {
      code: '0022',
      message: '无法修改留言数据',
      data: {}
    }
    return;
  }
  const {
    leaveMessageNumber,
    acceptedNumber,
    likedNumber,
    hotNumber
  } = r1[0];
  console.log('r1[0]: ', r1[0])
  const rankObj = {
    leaveMessageNumber: leaveMessageNumber - 1,
    acceptedNumber: isAccepted ? acceptedNumber - 1 : acceptedNumber,
    likedNumber: likedNumber - likeNum,
    hotNumber: hotNumber - (1 * hot1) - (isAccepted ? 1 * hot2 : 0) - (likeNum * hot3)
  };
  console.log('rankObj: ', rankObj)
  await DB.updateValue('leaveMessageRank', { userName }, rankObj)
  ctx.body = {
    code: '0000',
    message: '删除成功',
    data: r0[0]
  }
})

/**
 * 修改某条留言
 * @param {string} id 对应key值
 * @param {string} title 标题
 * @param {string} content 内容
 */
router.post('/reviseLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id, title, content } = ctx.request.body;
  if (!id || !title || !content) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言，修改失败',
      data: {}
    }
    return;
  }
  const updateData = { title, content };
  await DB.updateValue('leaveMessage', { key: id }, updateData);
  ctx.body = {
    code: '0000',
    message: '修改成功',
    data: Object.assign({}, r0[0], updateData)
  }
})

/**
 * 点赞某条留言
 * @param {string} id 对应key值
 */
router.post('/addLikeLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言，点赞失败',
      data: {}
    }
    return;
  }
  const newList = r0[0].likeList;
  if (newList.includes(userName)) {
    ctx.body = {
      code: '0020',
      message: '不能重复点赞',
      data: {}
    }
    return;
  }
  newList.push(userName);
  const updateData = {
    likeNum: r0[0].likeNum + 1,
    likeList: newList
  };
  await DB.updateValue('leaveMessage', { key: id }, updateData);
  const r1 = await DB.find('leaveMessageRank', { userName: r0[0].userName });
  if (!r1 || r1.length === 0) {
    ctx.body = {
      code: '0022',
      message: '无法修改留言数据',
      data: {}
    }
    return;
  }
  await DB.updateValue('leaveMessageRank', { userName: r0[0].userName }, {
    likedNumber: r1[0].likedNumber + 1,
    hotNumber: r1[0].hotNumber + 1 * hot3
  })
  ctx.body = {
    code: '0000',
    message: '点赞成功',
    data: Object.assign({}, r0[0], updateData)
  }
})

/**
 * 取消点赞某条留言
 * @param {string} id 对应key值
 */
router.post('/cutLikeLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言，取消失败',
      data: {}
    }
    return;
  }
  if (!r0[0].likeList.includes(userName)) {
    ctx.body = {
      code: '0020',
      message: '不能重复取消',
      data: {}
    }
    return;
  }
  const newList = r0[0].likeList.filter(item => item !== userName);
  const updateData = {
    likeNum: r0[0].likeNum - 1,
    likeList: newList
  };
  await DB.updateValue('leaveMessage', { key: id }, updateData);
  const r1 = await DB.find('leaveMessageRank', { userName: r0[0].userName });
  if (!r1 || r1.length === 0) {
    ctx.body = {
      code: '0022',
      message: '无法修改留言数据',
      data: {}
    }
    return;
  }
  await DB.updateValue('leaveMessageRank', { userName: r0[0].userName }, {
    likedNumber: r1[0].likedNumber - 1,
    hotNumber: r1[0].hotNumber - 1 * hot3
  })
  ctx.body = {
    code: '0000',
    message: '取消成功',
    data: Object.assign({}, r0[0], updateData)
  }
})

/**
 * 采纳某条留言
 * @param {string} id 对应key值
 */
router.post('/acceptLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言，采纳失败',
      data: {}
    }
    return;
  }
  const obj = { isAccepted: true };
  await DB.updateValue('leaveMessage', { key: id }, obj);
  const r1 = await DB.find('leaveMessageRank', { userName: r0[0].userName });
  if (!r1 || r1.length === 0) {
    ctx.body = {
      code: '0022',
      message: '无法修改留言数据',
      data: {}
    }
    return;
  }
  await DB.updateValue('leaveMessageRank', { userName: r0[0].userName }, {
    acceptedNumber: r1[0].acceptedNumber + 1,
    hotNumber: r1[0].acceptedNumber + 1 * hot2
  })
  ctx.body = {
    code: '0000',
    message: '采纳成功',
    data: Object.assign({}, r0[0], obj)
  }
})

/**
 * 取消采纳某条留言
 * @param {string} id 对应key值
 */
router.post('/noAcceptLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { key: id });
  if (!r0 || r0.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未获取到指定留言，拒绝采纳失败',
      data: {}
    }
    return;
  }
  const obj = { isAccepted: false };
  await DB.updateValue('leaveMessage', { key: id }, obj);
  const r1 = await DB.find('leaveMessageRank', { userName: r0[0].userName });
  if (!r1 || r1.length === 0) {
    ctx.body = {
      code: '0022',
      message: '无法修改留言数据',
      data: {}
    }
    return;
  }
  await DB.updateValue('leaveMessageRank', { userName: r0[0].userName }, {
    acceptedNumber: r1[0].acceptedNumber - 1,
    hotNumber: r1[0].acceptedNumber - 1 * hot2
  })
  ctx.body = {
    code: '0000',
    message: '取消成功',
    data: Object.assign({}, r0[0], obj)
  }
})

/**
 * 按照条件搜索用户留言
 * @param {string} user 按用户名/用户id查找
 * @param {boolean} isAccepted 是否被采纳
 * @param {number} startDate 按时间查找-开始时间戳
 * @param {number} endDate 按时间查找-结束时间戳
 */
router.get('/searchUserLeaveMessages', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { user, isAccepted, startDate, endDate } = ctx.query;
  let r0 = [];
  // 1.查询所有留言
  if (!user && !isAccepted && !startDate && !endDate) {
    r0 = await DB.find('leaveMessage');
  }
  // 2.按照用户名或者用户id查询留言
  else if (user && !isAccepted && !startDate && !endDate) {
    r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }] });
  }
  // 3.按照是否被采纳查找
  else if (!user && isAccepted && !startDate && !endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { isAccepted: true });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { isAccepted: false });
    }
  }
  // 4.按照开始时间查找
  else if (!user && !isAccepted && startDate && !endDate) {
    r0 = await DB.find('leaveMessage', { publishDate: { $gte: parseInt(startDate) } });
  }
  // 5. 按照结束时间查找
  else if (!user && !isAccepted && !startDate && endDate) {
    r0 = await DB.find('leaveMessage', { publishDate: { $lte: parseInt(endDate) } });
  }
  // 6. 开始时间 + 结束时间
  else if (!user && !isAccepted && startDate && endDate) {
    r0 = await DB.find('leaveMessage', { publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
  }
  // 7.指定用户 + 是否采纳
  else if (user && isAccepted && !startDate && !endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: true });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: false });
    }
  }
  // 8.按照指定用户+指定开始时间查找
  else if (user && !isAccepted && startDate && !endDate) {
    r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], publishDate: { $gte: parseInt(startDate) } });
  }
  // 9.按照指定用户 + 指定结束时间查找
  else if (user && !isAccepted && !startDate && endDate) {
    r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], publishDate: { $lte: parseInt(endDate) } });
  }
  // 10.指定用户 + 开始时间 + 结束时间查找
  else if (user && !isAccepted && startDate && endDate) {
    r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
  }
  // 11.是否采纳 + 开始时间
  else if (!user && isAccepted && startDate && !endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { isAccepted: true, publishDate: { $gte: parseInt(startDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { isAccepted: false, publishDate: { $gte: parseInt(startDate) } });
    }
  }
  // 12.是否采纳 + 结束时间
  else if (!user && isAccepted && !startDate && endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { isAccepted: true, publishDate: { $lte: parseInt(endDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { isAccepted: false, publishDate: { $lte: parseInt(endDate) } });
    }
  }
  // 13.是否采纳 + 开始时间 + 结束时间
  else if (!user && isAccepted && startDate && endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { isAccepted: true, publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { isAccepted: false, publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
    }
  }
  // 14.指定用户 + 是否采纳 + 开始时间
  else if (user && isAccepted && startDate && !endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: true, publishDate: { $gte: parseInt(startDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: false, publishDate: { $gte: parseInt(startDate) } });
    }
  }
  // 15.指定用户 + 是否采纳 + 结束时间
  else if (user && isAccepted && !startDate && endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: true, publishDate: { $lte: parseInt(endDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: false, publishDate: { $lte: parseInt(endDate) } });
    }
  }
  // 16.指定用户 + 是否采纳 + 开始时间 + 结束时间
  else if (user && isAccepted && startDate && endDate) {
    if (isAccepted === 'true') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: true, publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
    } else if (isAccepted === 'false') {
      r0 = await DB.find('leaveMessage', { $or: [{ userName: user }, { uid: parseInt(user) }], isAccepted: false, publishDate: { $gte: parseInt(startDate), $lte: parseInt(endDate) } });
    }
  }
  ctx.body = {
    code: '0000',
    message: '查询所有留言',
    data: r0
  }
})

/**
 * 获取我的留言
 */
router.get('/getMyLeaveMessage', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('leaveMessage', { userName });
  ctx.body = {
    code: '0000',
    message: '获取成功',
    data: r0
  }
})

/**
 * 获取所有被采纳留言
 */
router.get('/getAllAcceptLeaveMessage', async (ctx, next) => {
  const r0 = await DB.find('leaveMessage', { isAccepted: true });
  ctx.body = {
    code: '0000',
    message: '获取成功',
    data: r0
  }
})

module.exports = router;